package com.cgs.query.handler.statement

import com.cgs.query.configuration.QueryConfiguration
import com.cgs.query.domain.BoundSql
import com.cgs.query.exception.QueryException
import com.cgs.query.executor.ExecutionContext
import com.cgs.query.handler.StatementHandler
import java.sql.Connection
import java.sql.Statement
import mu.KotlinLogging

private val logger = KotlinLogging.logger { }

/**数据库桥接*/
abstract class BaseStatementHandler(
        val config: QueryConfiguration,
        executionContext: ExecutionContext) : StatementHandler {

    override val boundSql: BoundSql
    override val parameterHandler = config.parameterHandler
    val mappedStatement = executionContext.mappedStatement

    init {
        this.boundSql = parameterHandler.resolve(mappedStatement.executionObj, executionContext.param, executionContext)
    }

    /**获取statement以及设置超时*/
    override fun prepare(connection: Connection): Statement {
        try {
            return instantiateStatement(connection)
        } catch (e: Exception) {
            throw QueryException("准备Statement失败:${e.message}", e)
        }
    }

    abstract fun instantiateStatement(connection: Connection): Statement

    override fun close(statement: Statement?) {
        statement?.close()
    }
}

